#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>

#define BUF_SIZE 8192

void process_daemon()
{
	syslog(LOG_NOTICE, "Learner Daemon v0.1");
}

int main () {
	syslog(LOG_NOTICE, "Entering Learner Daemon");
	pid_t pid, sid;
	int fd, counter = 0;
	char buffer[BUF_SIZE];

	/* Fork off the parent process */       
	pid = fork();
	if (pid < 0)
		exit(EXIT_FAILURE);

	/* If we got a good PID, then
	we can exit the parent process. */
	if (pid > 0)
		exit(EXIT_SUCCESS);

	umask(0);

	/* Create a new SID for the child process */
	sid = setsid();
	if (sid < 0)
		/* Log any failure */
		exit(EXIT_FAILURE);

	/* Change the current working directory */
	if (chdir("/") < 0)
		exit(EXIT_FAILURE);

	/* Close standard file descriptors */
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	fd = open("/home/chladseb/learner_write", O_WRONLY | O_CREAT | O_TRUNC | O_APPEND,
		S_IRUSR | S_IWUSR);
	if (fd == -1)
		syslog(LOG_ERR, "[Learner] : File not open!");

	while (1) {
		process_daemon();
		/* Write some data to a file */
		/* write(file desc, buffer - data to be written, number of bytes
		   to write from buffer	*/
		//question: how to write to the buffer in an efficient way?
		counter++;
		write(fd, buffer, 1000);
		syslog(LOG_NOTICE, "counter: %d", counter);
		sleep(3);
	}

}
